﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace MessageProtocol
{
    public class MessageController
    {
        public static void Encode(Stream writer, Message msg)
        {
            writer.Write(msg.GetBytes(), 0, msg.GetSize());
        }

        public static Message Decode(Stream reader)
        {
            int totalRecv = 0;
            int sizeToRead = 16;
            byte[] hBuffer = new byte[sizeToRead];

            while (0 < sizeToRead)
            {
                byte[] buffer = new byte[sizeToRead];
                int recv = reader.Read(buffer, 0, sizeToRead);

                if (0 == recv)
                    return null;

                buffer.CopyTo(hBuffer, totalRecv);
                totalRecv += recv;
                sizeToRead -= recv;
            }

            Header header = new Header(hBuffer);

            totalRecv = 0;
            byte[] bBuffer = new byte[header.BODYLENGTH];
            sizeToRead = (int)header.BODYLENGTH;

            while (0 < sizeToRead)
            {
                byte[] buffer = new byte[sizeToRead];
                int recv = reader.Read(buffer, 0, sizeToRead);

                if (0 == recv)
                    return null;

                buffer.CopyTo(bBuffer, totalRecv);
                totalRecv += recv;
                sizeToRead -= recv;
            }

            ISerializable body = null;

            switch (header.MSGTYPE)
            {
                case MessageConstants.TYPE_REQUEST_GET:
                    body = new BodyResponse(bBuffer);
                    break;

                case MessageConstants.TYPE_REQUEST_SAVE:
                    body = new BodyRequest(bBuffer);
                    break;
    
                default:
                    break;
            }


            return new Message() { Header = header, Body = body };
        }

       
    }

}

    
